"""
lambda函数
格式： lambda 参数1，参数2...：运算
内置lambda函数：
max()
min()
sorted()
map()
reduce()
filter()
"""
s = lambda a, b: a + b
print(s(1, 2))
# 内置函数的匿名函数
# max sorted zip。。。
list1 = [1, 2, 4, 5, 6]
m = max(list1)
print(m)

list2 = [{"a": 1}, {"a": 2}, {"a": 3}]
m2 = max(list2, key=lambda x: x["a"])
print(m2)

# map函数遍历列表
list3 = [1, 2, 3, 4]
result = map(lambda x: x + 2, list3)
print(list(result))
# 加入三目运算
func = lambda x: x if x % 2 == 0 else x + 1
print(func(5))
print(func(4))

# reduce:对列表中的元素进行加减乘除运算的函数
from functools import reduce

t = (1, 2, 3, 4, 5)
result = reduce(lambda x, y: x + y, t)
print(result)
t2 = (1,)
result = reduce(lambda x, y: x + y, t2, 10)
print(result)

# filter：过滤数据
list5 = [1, 2, 3, 12, 42, 12, 57, 78]
result = filter(lambda x: x > 10, list5)
print(list(result))
# 找出年龄大于20岁的人
user = [
    {"username": "高嘉银", "age": 10},
    {"username": "廖立晴", "age": 30},
    {"username": "黄帮派", "age": 40},
    {"username": "蒋云超", "age": 50},
    {"username": "詹姆斯", "age": 70},
]
result = filter(lambda x: x["age"] > 20, user)
print(list(result))
# 按照年龄从小到大排序
result = sorted(user, key=lambda x: x["age"], reverse=True)
print(list(result))
